package com.xc.hotelmgr.consumermq.service.mq.Impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.xc.hotelmgr.consumermq.pojo.mq.*;
import com.xc.hotelmgr.consumermq.pojo.mybatis.*;
import com.xc.hotelmgr.consumermq.pojo.redis.StoreHotelInfo;
import com.xc.hotelmgr.consumermq.service.FeignService.*;
import com.xc.hotelmgr.consumermq.service.mq.MQService;
import com.xc.hotelmgr.consumermq.service.mybatis.DtStoreService;
import com.xc.hotelmgr.consumermq.service.mybatis.OpRPGroupService;
import com.xc.hotelmgr.consumermq.service.mybatis.OpTaskStatusService;
import com.xc.hotelmgr.consumermq.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MQServiceImpl implements MQService {

    private static String STORE_HOTEL_TASK_CODE = "STOREHOTEL";

    @Autowired
    private AliFeignService aliFeignService;

    @Autowired
    private AliFeignServiceOnece aliFeignServiceOnece;

    @Autowired
    private MtFeginServiceOence mtFeginServiceOence;

    @Autowired
    private MtFeginService mtFeginService;

    @Autowired
    private DtStoreService dtStoreService;

    @Autowired
    private OpTaskStatusService opTaskStatusService;

    @Autowired
    private CtripFeginService ctripFeginService;

    @Autowired
    private CtripFeginServiceOnece ctripFeginServiceOnece;

    @Autowired
    private RedisFeignService redisFeignService;

    @Autowired
    private OpRPGroupService opRPGroupService;

    @Autowired
    private SendMessageMgr sendMessageMgr;

    @Autowired
    RedisUtils redisUtils;

    @Override
    public void hotelSendAll(SendAll sendAll, String queueName) {
        String appKey = Util.appkey(queueName);
        Long hotelId = sendAll.getHotelId();
        int storeId = sendAll.getStoreId();
        DtStore dtStore = dtStoreService.getByAppKey(appKey);
        String secret = dtStore.getSecret();
        String sessionKey = dtStore.getSessionkey();
        if (hotelId == -1) { // 任务结束条件
            OpTaskStatus opTaskStatus = new OpTaskStatus();
            opTaskStatus.setArchive(1);
            opTaskStatus.setStorId(storeId);
            opTaskStatus.setTaskCode(STORE_HOTEL_TASK_CODE);
            opTaskStatus.setCompTime(new Date());
            opTaskStatus.setStatus(1);
            opTaskStatus.setId(sendAll.getTaskId());
            opTaskStatusService.updateIgnoreNullByStoreIdAndArchive(opTaskStatus); // 执行status状态改变为1（0执行中）
        } else {
            sendAll.setAppKey(appKey);
            sendAll.setSecret(secret);
            sendAll.setSessionKey(sessionKey);
            opTaskStatusService.commPercentAdd(sendAll.getTaskId()); // 执行数量相加
            aliFeignServiceOnece.pushHotelAllSend(sendAll);
        }
    }

    /**
     * 酒店上下架
     *
     * @param upDown
     * @param queueName
     */
    @Override
    public void hotelUpDown(UpDown upDown, String queueName) {
        Long hotelId = upDown.getHotelId();
        int storeId = upDown.getStoreId();
        String appKey = Util.appkey(queueName);
        DtStore dtStore = dtStoreService.getByAppKey(appKey);
        String secret = dtStore.getSecret();
        String sessionKey = dtStore.getSessionkey();

        if (hotelId == -1) {
            OpTaskStatus opTaskStatus = new OpTaskStatus();
            opTaskStatus.setArchive(1);
            opTaskStatus.setStorId(storeId);
            opTaskStatus.setTaskCode(STORE_HOTEL_TASK_CODE);
            opTaskStatus.setCompTime(new Date());
            opTaskStatus.setStatus(1);
            opTaskStatus.setId(upDown.getTaskId());
            opTaskStatusService.updateIgnoreNullByStoreIdAndArchive(opTaskStatus); // 执行status状态改变为1（0执行中）
        } else {
            upDown.setAppKey(appKey);
            upDown.setSecret(secret);
            upDown.setSessionKey(sessionKey);
            aliFeignServiceOnece.hotelStateSend(upDown);
            opTaskStatusService.commPercentAdd(upDown.getTaskId()); // 执行数量相加
        }
    }

    @Override
    public void hotelCallBack(HotelCallBack hotelCallBack, String queueName) {
        //1、根据店铺信息(storeId)过滤属于本店铺的数据
        List<HistStoreOurPlanRP> histStoreOurPlanRPs = hotelCallBack.getHistStoreOurPlanRPs();
        String appKey = Util.appkey(queueName);
        DtStore dtStore = dtStoreService.getByAppKey(appKey);
        Integer storeId = dtStore.getId();
        histStoreOurPlanRPs = histStoreOurPlanRPs.stream().filter((item)-> item.getStoreId().equals(storeId)).collect(Collectors.toList());
        //如果该店铺没有上架给酒店则直接返回
        if(histStoreOurPlanRPs.isEmpty()){
            return;
        }

        //2、删除redis(删除店铺下已经失效的价格政策的加价配置)
        StoreHotelInfo storeHotelInfo = new StoreHotelInfo();
        storeHotelInfo.setStoreId(dtStore.getId());
        storeHotelInfo.setAppKey(dtStore.getAppkey());
        storeHotelInfo.setHotelId(hotelCallBack.getHotelId());
        List<Long> rps =  histStoreOurPlanRPs.stream().map(HistStoreOurPlanRP::getRpCode).distinct().collect(Collectors.toList());
        if(!rps.isEmpty()) {
            storeHotelInfo.setRpList(rps);
            redisFeignService.delStoreRpSaveUseAddPriceCfg(storeHotelInfo);
        }
        //保存最新的rp使用的加价配置
        redisFeignService.storeRpSaveUseAddPriceCfg(storeHotelInfo);
        //3、推送酒店信息
        SendAll sendAll = new SendAll();
        sendAll.setAppKey(appKey);
        sendAll.setHotelId(hotelCallBack.getHotelId());
        sendAll.setSecret(dtStore.getSecret());
        sendAll.setTaskId(Constant.ChangeHotelTaskId.PUSH.getValue());
        sendAll.setSessionKey(dtStore.getSessionkey());
        sendAll.setStoreId(dtStore.getId());
        aliFeignService.pushHotelAll(sendAll);
        if(!storeHotelInfo.getRpList().isEmpty()) {
            storeHotelInfo.getRpList().clear();
        }

        //4、删除店铺上无效的rp
        DelRpMQ delRpMQ = null;
        for(HistStoreOurPlanRP histStoreOurPlanRP : histStoreOurPlanRPs){
            //有自定义价格计划
            if(histStoreOurPlanRP.getOurPlanId() != null){
                delRpMQ = new DelRpMQ();
                delRpMQ.setRpId(histStoreOurPlanRP.getRpCode());
                delRpMQ.setOpOurRateplanId(histStoreOurPlanRP.getOurPlanId());
                delRpMQ.setAppKey(appKey);
                delRpMQ.setSecret(dtStore.getSecret());
                delRpMQ.setSessionKey(dtStore.getSessionkey());
                delRpMQ.setTaskId(Constant.ChangeHotelTaskId.DEL_RP.getValue());
                aliFeignService.deleteRateplan(delRpMQ);
                //无自定义价格计划
            }else {
                delRpMQ = new DelRpMQ();
                delRpMQ.setRpId(histStoreOurPlanRP.getRpCode());
                delRpMQ.setOpOurRateplanId(0);
                delRpMQ.setAppKey(appKey);
                delRpMQ.setSecret(dtStore.getSecret());
                delRpMQ.setSessionKey(dtStore.getSessionkey());
                delRpMQ.setTaskId(Constant.ChangeHotelTaskId.DEL_RP.getValue());
                aliFeignService.deleteRateplan(delRpMQ);
            }
        }
    }

    @Override
    public void roomCallBack() {

    }

    @Override
    public void rpCallBack(RpCallBack rpCallBack, String queueName) {
        String appKey = Util.appkey(queueName);
        DtStore dtStore = dtStoreService.getByAppKey(appKey);
        rpCallBack.setAppKey(appKey);
        rpCallBack.setSecret(dtStore.getSecret());
        rpCallBack.setSessionKey(dtStore.getSessionkey());
        rpCallBack.setStoreId(dtStore.getId());
        aliFeignService.callbackRp(rpCallBack);
    }

    @Override
    public void ratesCallBack(RatesCallBack ratesCallBack, String queueName) {
        String appKey = Util.appkey(queueName);
        DtStore dtStore = dtStoreService.getByAppKey(appKey);
        Integer id = dtStore.getId();
        ratesCallBack.setAppKey(appKey);
        ratesCallBack.setSecret(dtStore.getSecret());
        ratesCallBack.setSessionKey(dtStore.getSessionkey());
        ratesCallBack.setSessionKey(dtStore.getSessionkey());
        ratesCallBack.setStoreId(id);
        aliFeignService.callbackRates(ratesCallBack);
    }

    /**
     * 美团全量、分组酒店拉取，如果是分组酒店拉取推送，则调用阿里推送服务（datapusher-ali-onece）/hotel/send_all，推送
     * @param taskHotelList
     */
    @Override
    public void pullHotel(TaskHotelList taskHotelList) throws InterruptedException {
        List<Long> hotelList = taskHotelList.getHotelList();
        int htNum = hotelList.size();
        Long taskId = taskHotelList.getTaskId();
        List<HistStoreOurPlanRP> histStoreOurPlanRPs = Lists.newArrayList();
        Boolean isGroup = taskHotelList.getIsGroup();
        Integer retryCnt = 1;
        boolean doSuccess = false;
        boolean saveRedisSuccess = false;
        if (!hotelList.isEmpty()) {
            if(isGroup) {
                //查询酒店所属店铺信息及酒店下历史rp信息
                histStoreOurPlanRPs = opRPGroupService.selectByStoreHotelId(taskHotelList.getStoreId(), hotelList.get(0));
                //删除历史信息
                StoreHotelInfo storeHotelInfo = new StoreHotelInfo();
                storeHotelInfo.setHotelId(hotelList.get(0));
                List<Long> delRps = histStoreOurPlanRPs.stream().map(HistStoreOurPlanRP::getRpCode).distinct().collect(Collectors.toList());
                if (!delRps.isEmpty()) {
                    storeHotelInfo.setRpList(delRps);
                    try {
                        redisFeignService.deleteDbRPByIds(storeHotelInfo);
                        doSuccess = true;
                    } catch (Exception ex) {
                        log.error("保存redis失败：酒店id：{}，异常信息：{}", storeHotelInfo, ex);
                        doSuccess = false;
                    }
                    //出错重试
                    retryCnt = 1;
                    while (!doSuccess && retryCnt < Constant.TRYCNT) {
                        Thread.sleep(Constant.SLEEP_TIME);
                        try {
                            redisFeignService.deleteDbRpByHotelId(storeHotelInfo);
                            doSuccess = true;
                        } catch (Exception ex) {
                            doSuccess = false;
                        }
                        retryCnt = retryCnt + 1;
                    }
                }
            }
            //全量拉取只拉取酒店信息
            try{
                mtFeginServiceOence.getHotel(taskHotelList);
                if(isGroup) {
                    mtFeginServiceOence.getRoom(taskHotelList);
                    mtFeginServiceOence.getGoods(taskHotelList);
                }
                doSuccess = true;
            }catch (Exception ex){
                log.error("拉取酒店相关信息失败：酒店id：{}，异常信息：{}",taskHotelList,ex);
                doSuccess = false;
            }
            //出错重试
            retryCnt = 1;
            while (!doSuccess && retryCnt < Constant.TRYCNT) {
                Thread.sleep(Constant.SLEEP_TIME);
                try{
                    mtFeginServiceOence.getHotel(taskHotelList);
                    if(isGroup) {
                        mtFeginServiceOence.getRoom(taskHotelList);
                        mtFeginServiceOence.getGoods(taskHotelList);
                    }
                    doSuccess = true;
                }catch (Exception ex){
                    doSuccess = false;
                }
                retryCnt = retryCnt + 1;
            }

            //保存相关信息到redis
            for (Long hotelId : hotelList) {
                StoreHotelInfo storeHotelInfo = new StoreHotelInfo();
                storeHotelInfo.setStoreId(taskHotelList.getStoreId());
                storeHotelInfo.setAppKey(taskHotelList.getAppKey());
                storeHotelInfo.setHotelId(hotelId);
                retryCnt = 1;
                saveRedisSuccess = saveRedis(storeHotelInfo);
                //重试保存到redis
                while (!saveRedisSuccess && retryCnt < Constant.TRYCNT){
                    Thread.sleep(Constant.SLEEP_TIME);
                    saveRedisSuccess = saveRedis(storeHotelInfo);
                    retryCnt = retryCnt + 1;
                }
            }
            //如果是分组拉取，推送酒店
            if (isGroup) {
                //计算失效出失效的rp，删除redis和数据库下无效rp
                //查询该酒店下最新的RP
                List<Long> rPs = opRPGroupService.selectByHotelId(hotelList.get(0));
                List<Long> histRps = histStoreOurPlanRPs.stream().map(HistStoreOurPlanRP::getRpCode).distinct().collect(Collectors.toList());
                //计算无效的rp
                histRps.removeAll(rPs);
                if(!histRps.isEmpty()) {
                    StoreHotelInfo storeHotelInfo = new StoreHotelInfo();
                    storeHotelInfo.setAppKey(taskHotelList.getAppKey());
                    storeHotelInfo.setStoreId(taskHotelList.getStoreId());
                    storeHotelInfo.setHotelId(hotelList.get(0));
                    storeHotelInfo.setRpList(histRps);
                    redisFeignService.delRpStoreHtlRoomSave(storeHotelInfo);
                    redisFeignService.delStoreRpSaveUseAddPriceCfg(storeHotelInfo);
                }

                Integer storeId = taskHotelList.getStoreId();
                String appKey = taskHotelList.getAppKey();
                String sessionKey = taskHotelList.getSessionKey();
                String secret = taskHotelList.getSecret();
                for (Long hotelId : hotelList) {
                    SendAll sendAll = new SendAll();
                    sendAll.setAppKey(appKey);
                    sendAll.setHotelId(hotelId);
                    sendAll.setSecret(secret);
                    sendAll.setTaskId(taskId);
                    sendAll.setSessionKey(sessionKey);
                    sendAll.setStoreId(storeId);
                    //如果没有成功保存到redis则不推送
                    if(saveRedisSuccess) {
                        aliFeignServiceOnece.pushHotelAllSend(sendAll);
                    }
                }
                //删除店铺上无效的rp
                histStoreOurPlanRPs = histStoreOurPlanRPs.stream().filter((item)->{
                    if(rPs.contains(item.getRpCode())){
                        return false;
                    }else {
                        return true;
                    }
                }).collect(Collectors.toList());
                DelRpMQ delRpMQ = null;
                for(HistStoreOurPlanRP histStoreOurPlanRP : histStoreOurPlanRPs){
                    //有自定义价格计划
                    if(histStoreOurPlanRP.getOurPlanId() != null){
                        delRpMQ = new DelRpMQ();
                        delRpMQ.setRpId(histStoreOurPlanRP.getRpCode());
                        delRpMQ.setOpOurRateplanId(histStoreOurPlanRP.getOurPlanId());
                        delRpMQ.setAppKey(appKey);
                        delRpMQ.setSecret(secret);
                        delRpMQ.setSessionKey(sessionKey);
                        delRpMQ.setTaskId(Constant.ChangeHotelTaskId.DEL_RP.getValue());
                        aliFeignServiceOnece.deleteRateplanSend(delRpMQ);
                        //无自定义价格计划
                    }else {
                        delRpMQ = new DelRpMQ();
                        delRpMQ.setRpId(histStoreOurPlanRP.getRpCode());
                        delRpMQ.setOpOurRateplanId(0);
                        delRpMQ.setAppKey(appKey);
                        delRpMQ.setSecret(secret);
                        delRpMQ.setSessionKey(sessionKey);
                        delRpMQ.setTaskId(Constant.ChangeHotelTaskId.DEL_RP.getValue());
                        aliFeignServiceOnece.deleteRateplanSend(delRpMQ);
                    }
                }
            }
            OpTaskStatus opTaskStatus = new OpTaskStatus();
            opTaskStatus.setId(taskId);
            opTaskStatus.setCompPercent(htNum);
            opTaskStatusService.updateByAllHotelMount(opTaskStatus);

        } else {
            log.info("消息队列为空,酒店拉取完毕");
            //判断消息队列是否为空，如果为空，程序执行完毕
            OpTaskStatus opTaskStatus = new OpTaskStatus();
            opTaskStatus.setArchive(1);
            opTaskStatus.setStatus(1);
            opTaskStatus.setCompTime(new Date());
            opTaskStatus.setId(taskId);
            opTaskStatusService.updateIgnoreNullByStoreIdAndArchive(opTaskStatus);
        }
    }

    /**
     * 携程全量、分组酒店拉取，如果是分组酒店拉取推送，则调用阿里推送服务（datapusher-ali-onece）/hotel/send_all，推送
     * @param taskHotelList
     */
    @Override
    public void ctripSendAll(TaskHotelList taskHotelList) throws InterruptedException {
        List<Long> hotelList = taskHotelList.getHotelList();
        int htNum = hotelList.size();
        Boolean isGroup = taskHotelList.getIsGroup();
        Integer retryCnt = 0;
        boolean doSuccess = false;
        boolean saveRedisSuccess = false;
        List<HistStoreOurPlanRP> histStoreOurPlanRPs = Lists.newArrayList();
        if(!hotelList.isEmpty()){
            if(isGroup) {
                //查询酒店所属店铺信息及酒店下历史rp信息
                histStoreOurPlanRPs = opRPGroupService.selectByStoreHotelId(taskHotelList.getStoreId(), hotelList.get(0));
                //删除历史信息
                StoreHotelInfo storeHotelInfo = new StoreHotelInfo();
                storeHotelInfo.setHotelId(hotelList.get(0));
                List<Long> delRps = histStoreOurPlanRPs.stream().map(HistStoreOurPlanRP::getRpCode).distinct().collect(Collectors.toList());
                if(!delRps.isEmpty()) {
                    storeHotelInfo.setRpList(delRps);
                    try {
                        redisFeignService.deleteDbRPByIds(storeHotelInfo);
                        doSuccess = true;
                    } catch (Exception ex) {
                        log.error("保存Redis失败：酒店id：{}，异常信息：{}", storeHotelInfo, ex);
                        doSuccess = false;
                    }
                    //出错重试
                    retryCnt = 0;
                    while (!doSuccess && retryCnt < Constant.TRYCNT) {
                        Thread.sleep(Constant.SLEEP_TIME);
                        try {
                            redisFeignService.deleteDbRPByIds(storeHotelInfo);
                            doSuccess = true;
                        } catch (Exception ex) {
                            doSuccess = false;
                        }
                        retryCnt = retryCnt + 1;
                    }
                }
            }

            //获取酒店信息
            try {
                taskHotelList.setTaskCode((long) 21);
                ctripFeginServiceOnece.pullAll(taskHotelList);
                //全量拉取只拉取酒店信息
                if (isGroup) {
                    //获取房型信息
                    taskHotelList.setTaskCode((long) 22);
                    ctripFeginServiceOnece.pullAll(taskHotelList);
                    //价量态信息
                    taskHotelList.setTaskCode((long) 23);
                    ctripFeginServiceOnece.pullAll(taskHotelList);
                }
                doSuccess = true;
            }catch (Exception ex){
                log.error("拉取酒店相关信息失败：酒店id：{}，异常信息：{}",taskHotelList,ex);
                doSuccess = false;
            }

            //出错重试
            retryCnt = 0;
            while (!doSuccess && retryCnt < Constant.TRYCNT) {
                Thread.sleep(Constant.SLEEP_TIME);
                try {
                    taskHotelList.setTaskCode((long) 21);
                    ctripFeginService.pullAll(taskHotelList);
                    //全量拉取只拉取酒店信息
                    if (isGroup) {
                        //获取房型信息
                        taskHotelList.setTaskCode((long) 22);
                        ctripFeginService.pullAll(taskHotelList);
                        //价量态信息
                        taskHotelList.setTaskCode((long) 23);
                        ctripFeginService.pullAll(taskHotelList);
                    }
                    doSuccess = true;
                }catch (Exception ex){
                    doSuccess = false;
                }
                retryCnt = retryCnt + 1;
            }

            //保存相关信息到redis
            for (Long hotelId : hotelList) {
                StoreHotelInfo storeHotelInfo = new StoreHotelInfo();
                storeHotelInfo.setStoreId(taskHotelList.getStoreId());
                storeHotelInfo.setAppKey(taskHotelList.getAppKey());
                storeHotelInfo.setHotelId(hotelId);
                //重试确保数据保存到redis
                retryCnt = 0;
                saveRedisSuccess = saveRedis(storeHotelInfo);
                while (!saveRedisSuccess && retryCnt < Constant.TRYCNT){
                    Thread.sleep(Constant.SLEEP_TIME);
                    saveRedisSuccess = saveRedis(storeHotelInfo);
                    retryCnt = retryCnt + 1;
                }

            }
            //如果是分组拉取，推送酒店
            if (isGroup){
                //计算失效出失效的rp，删除redis和数据库下无效rp
                //查询该酒店下最新的RP
                List<Long> rPs = opRPGroupService.selectByHotelId(hotelList.get(0));
                List<Long> histRps = histStoreOurPlanRPs.stream().map(HistStoreOurPlanRP::getRpCode).distinct().collect(Collectors.toList());
                //计算无效的rp
                histRps.removeAll(rPs);
                if(!histRps.isEmpty()) {
                    StoreHotelInfo storeHotelInfo = new StoreHotelInfo();
                    storeHotelInfo.setAppKey(taskHotelList.getAppKey());
                    storeHotelInfo.setStoreId(taskHotelList.getStoreId());
                    storeHotelInfo.setHotelId(hotelList.get(0));
                    storeHotelInfo.setRpList(histRps);
                    redisFeignService.delRpStoreHtlRoomSave(storeHotelInfo);
                    redisFeignService.delStoreRpSaveUseAddPriceCfg(storeHotelInfo);
                }
                Integer storeId = taskHotelList.getStoreId();
                String appKey = taskHotelList.getAppKey();
                String sessionKey = taskHotelList.getSessionKey();
                String secret = taskHotelList.getSecret();
                for (Long hotelId : hotelList) {
                    Long taskId = taskHotelList.getTaskId();
                    SendAll sendAll = new SendAll();
                    sendAll.setAppKey(appKey);
                    sendAll.setHotelId(hotelId);
                    sendAll.setSecret(secret);
                    sendAll.setTaskId(taskId);
                    sendAll.setSessionKey(sessionKey);
                    sendAll.setStoreId(storeId);
                    sendAll.setSendType(-1);
                    //如果保存redis成功，则推送酒店
                    if(saveRedisSuccess) {
                        aliFeignServiceOnece.pushHotelAllSend(sendAll);
                    }
                }
                //删除店铺上无效的rp
                histStoreOurPlanRPs = histStoreOurPlanRPs.stream().filter((item)->{
                    if(rPs.contains(item.getRpCode())){
                        return false;
                    }else {
                        return true;
                    }
                }).collect(Collectors.toList());
                DelRpMQ delRpMQ = null;
                for(HistStoreOurPlanRP histStoreOurPlanRP : histStoreOurPlanRPs){
                    //有自定义价格计划
                    if(histStoreOurPlanRP.getOurPlanId() != null){
                        delRpMQ = new DelRpMQ();
                        delRpMQ.setRpId(histStoreOurPlanRP.getRpCode());
                        delRpMQ.setOpOurRateplanId(histStoreOurPlanRP.getOurPlanId());
                        delRpMQ.setAppKey(appKey);
                        delRpMQ.setSecret(secret);
                        delRpMQ.setSessionKey(sessionKey);
                        delRpMQ.setTaskId(Constant.ChangeHotelTaskId.DEL_RP.getValue());
                        aliFeignServiceOnece.deleteRateplanSend(delRpMQ);
                        //无自定义价格计划
                    }else {
                        delRpMQ = new DelRpMQ();
                        delRpMQ.setRpId(histStoreOurPlanRP.getRpCode());
                        delRpMQ.setOpOurRateplanId(0);
                        delRpMQ.setAppKey(appKey);
                        delRpMQ.setSecret(secret);
                        delRpMQ.setSessionKey(sessionKey);
                        delRpMQ.setTaskId(Constant.ChangeHotelTaskId.DEL_RP.getValue());
                        aliFeignServiceOnece.deleteRateplanSend(delRpMQ);
                    }
                }
            }
            OpTaskStatus opTaskStatus = new OpTaskStatus();
            opTaskStatus.setId(taskHotelList.getTaskId());
            opTaskStatus.setCompPercent(htNum);
            opTaskStatusService.updateByAllHotelMount(opTaskStatus);
        }else {
            log.info("消息队列为空,酒店拉取完毕");
            //判断消息队列是否为空，如果为空，程序执行完毕
            OpTaskStatus opTaskStatus = new OpTaskStatus();
            opTaskStatus.setArchive(0);
            opTaskStatus.setStatus(1);
            opTaskStatus.setCompTime(new Date());
            opTaskStatusService.updateIgnoreNullByStoreIdAndArchive(opTaskStatus);
        }
    }

    private boolean saveRedis(StoreHotelInfo storeHotelInfo) {
        try {
            redisFeignService.rpStoreHtlRoomSave(storeHotelInfo);
            redisFeignService.storeHtlSaveOurPlan(storeHotelInfo);
            redisFeignService.storeRpSaveUseAddPriceCfg(storeHotelInfo);
            redisFeignService.rpsSave(storeHotelInfo);
            return true;
        }catch (Exception ex){
            log.error("保存redis失败：酒店id：{}，异常信息：{}",storeHotelInfo,ex);
            return  false;
        }
    }

    /**
     * 消息转移，从 消息队列 hotel_id_list_all（暂存所有酒店ID），转移消息 到 hotel_id_list（实际拉取队列）队列进行拉取从
     * 前端 hotelIdListAll(on_off/{status})可以暂停（移除对 hotel_id_list_all 队列的监听，转移
     * @param taskHotelList
     * @throws InterruptedException
     */
    @Override
    public void moveHtId(TaskHotelList taskHotelList) throws InterruptedException {
//        mtFeginServiceOence.moveHtId(taskHotelList);
        sendMessageMgr.sendMessage(MqType.HTLIDLIST, taskHotelList, "");
        Thread.sleep(1000);
    }

    @Override
    public boolean rpDel(DelRpMQ delRpMQ, String queueName) {
        String appKey = Util.appkey(queueName);
        DtStore dtStore = dtStoreService.getByAppKey(appKey);
        String secret = dtStore.getSecret();
        String sessionKey = dtStore.getSessionkey();
        int storeId = dtStore.getId();
        Long rpId = delRpMQ.getRpId();
        if(rpId==-1) {
            OpTaskStatus opTaskStatus = new OpTaskStatus();
            opTaskStatus.setArchive(1);
            opTaskStatus.setStorId(storeId);
            opTaskStatus.setTaskCode(STORE_HOTEL_TASK_CODE);
            opTaskStatus.setCompTime(new Date());
            opTaskStatus.setStatus(1);
            opTaskStatus.setId(delRpMQ.getTaskId());
            opTaskStatusService.updateIgnoreNullByStoreIdAndArchive(opTaskStatus); // 执行status状态改变为1（0执行中）
            return true;
        }else {
            delRpMQ.setAppKey(appKey);
            delRpMQ.setSecret(secret);
            delRpMQ.setSessionKey(sessionKey);
            boolean result3 = aliFeignServiceOnece.deleteRateplanSend(delRpMQ);
            if(!result3){
                delRpMQ.setDelCnt(delRpMQ.getDelCnt() + 1);
                if(delRpMQ.getDelCnt() < Constant.TRYCNT){
                    sendMessageMgr.sendMessage(MqType.DELRP,delRpMQ,appKey);
                }
            }
            int result2 = opTaskStatusService.commPercentAdd(delRpMQ.getTaskId()); // 执行数量相加
            return result2 > 1 & result3;
        }
    }

    @Override
    public void citySendAll(TaskHotelList taskHotelList) {
        //设置任务id根据城市id获取酒店数据
        taskHotelList.setTaskCode((long) 1);
        ctripFeginService.pullAll(taskHotelList);
    }

    /**
     * 携程价量态请求获取数据
     * @param jsonObject
     */
    @Override
    public void upHtId(JSONObject jsonObject) {
        ctripFeginService.upPSQ(jsonObject);
    }

    /**
     * 酒店变化处理
     *              //1、查询酒店所属店铺信息及酒店下历史rp信息
     *             //2、删除数据库数据（房型、rp、rps)
     *             //3、拉取（酒店、房型、rp、rps)
     *             //4、计算失效出失效的rp，删除redis(无效rp所属的店铺、酒店、房型信息)
     *             //5、存储redis到rp所属的店铺、酒店、房型
     *             //6、将店铺信息、酒店信息、失效rp信息发送到call_back消息队列
     * @param htHotelinfo
     */
    @Override
    public void dealAndSend(HtHotelinfo htHotelinfo) {
        //1、查询酒店所属店铺信息及酒店下历史rp信息
        List<HistStoreOurPlanRP> histStoreOurPlanRPs = opRPGroupService.selectHchsoByHotelId(htHotelinfo.getId());
        HotelCallBack hotelCallBack = new HotelCallBack();
        hotelCallBack.setHotelId(htHotelinfo.getId());


        //2、删除数据库数据（房型、rp、rps)
        StoreHotelInfo storeHotelInfo = new StoreHotelInfo();
        storeHotelInfo.setHotelId(htHotelinfo.getId());
        List<Long> delRps = histStoreOurPlanRPs.stream().map(HistStoreOurPlanRP::getRpCode).distinct().collect(Collectors.toList());
        if(!delRps.isEmpty()) {
            storeHotelInfo.setRpList(delRps);
            redisFeignService.deleteDbRPByIds(storeHotelInfo);
        }

        //3、拉取（酒店、房型、rp、rps)
        List<Long> hotelIdList = new ArrayList<>();
        TaskHotelList taskHotelList = new TaskHotelList();
        hotelIdList.add(hotelCallBack.getHotelId());
        taskHotelList.setHotelList(hotelIdList);
        //携程酒店
        if(hotelCallBack.getHotelId().toString().substring(0,2).equals("-1")){
            taskHotelList.setHotelList(taskHotelList.getHotelList());
            String ctripOrderChannels = redisUtils.get("ctripOrderChannels");
            List<DtOrderChannelsEntity> channels = JSONObject.parseObject(ctripOrderChannels, new TypeReference<List<DtOrderChannelsEntity>>(){});
            Calendar calendar = Calendar.getInstance();
            int index = calendar.get(Calendar.HOUR) % channels.size();
            int AID = Integer.parseInt(channels.get(index).getAccessKey());
            int SID = channels.get(index).getSid();
            String KEY = channels.get(index).getSecretKey();
            taskHotelList.setAID(AID);
            taskHotelList.setSID(SID);
            taskHotelList.setKEY(KEY);
            //拉取酒店信息
            taskHotelList.setTaskCode((long) 21);
            ctripFeginService.pullAll(taskHotelList);
            //拉取房型信息
            taskHotelList.setTaskCode((long) 22);
            ctripFeginService.pullAll(taskHotelList);
            //拉取价量态信息
            taskHotelList.setTaskCode((long) 23);
            ctripFeginService.pullAll(taskHotelList);
        }else {//美团酒店
            mtFeginService.getHotel(taskHotelList);
            mtFeginService.getRoom(taskHotelList);
            mtFeginService.getGoods(taskHotelList);
        }

        // 4、计算失效出失效的rp，删除redis(无效rp所属的店铺、酒店、房型信息)
        //查询该酒店下最新的RP
        List<Long> rPs = opRPGroupService.selectByHotelId(hotelCallBack.getHotelId());
        List<Long> histRps = histStoreOurPlanRPs.stream().map(HistStoreOurPlanRP::getRpCode).collect(Collectors.toList());
        //计算无效的rp
        histRps.removeAll(rPs);
        histRps = histRps.stream().distinct().collect(Collectors.toList());
        if(!histRps.isEmpty()) {
            storeHotelInfo.setRpList(histRps);
            redisFeignService.delRpStoreHtlRoomSave(storeHotelInfo);
        }
        //5、保存到redis(rp所使用的店铺、酒店、房型以及rps）
        redisFeignService.rpStoreHtlRoomSave(storeHotelInfo);
        redisFeignService.rpsSave(storeHotelInfo);

        //6、将店铺信息、酒店信息、失效rp信息发送到call_back消息队列

        histStoreOurPlanRPs = histStoreOurPlanRPs.stream().filter((item)->{
            if(rPs.contains(item.getRpCode())){
                return false;
            }else {
                return true;
            }
        }).collect(Collectors.toList());
        hotelCallBack.setHistStoreOurPlanRPs(histStoreOurPlanRPs);
        sendMessageMgr.sendMessage(MqType.CALLBACKHOTEL, hotelCallBack, "");
    }

}
